package com.ywd.platform.netty.config;

import com.ywd.platform.netty.jt080.service.*;
import com.ywd.platform.service.impl.DeviceServiceImpl;
import com.ywd.platform.service.impl.VehicleServiceImpl;
import com.ywd.platform.service.impl.VehicleTrackRecordServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Netty通道初始化类
 * 用于配置新连接的ChannelPipeline
 */
@AllArgsConstructor
@Slf4j
//@ChannelHandler.Sharable
@Component
public class JT808ChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final static int readerIdleTime = 180;        // 读空闲超时 3分钟
    private final static int writerIdleTime = 180;        // 写空闲超时
    private final static int allIdleTime = 180;           // 总空闲超时
    private final static int maxFrameLength = 2048;       // 最大帧长度2KB

    private final TerminalService terminalService;
    private final TerminalConnectionManager connectionManager; // 添加连接管理器


    /**
     * 初始化管道
     */
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        //入站数据流程：
        //ByteBuf → IdleStateHandler → JT808FrameDecoder → JT808Decoder → JT808ServerHandler
        //出站数据流程：
        //JT808ServerHandler → JT808Encoder → ExceptionHandler → Socket

        // ================ 入站处理器 (从上到下执行) ================
        // 1. 空闲检测 (双向)
        pipeline.addLast("idleStateHandler",
                new IdleStateHandler(
                        readerIdleTime,
                        writerIdleTime,
                        allIdleTime,
                        TimeUnit.SECONDS));

        // 2. 帧解码器 (处理粘包/拆包)
        pipeline.addLast("frameDecoder", new JT808FrameDecoder());
        // 3. 协议解码器 (ByteBuf -> JT808Message)
        pipeline.addLast("decoder", new JT808Decoder());
        // 4. 业务处理器 (JT808Message)
        pipeline.addLast("handler", new JT808ServerHandler(terminalService,connectionManager));
        // ================ 出站处理器 (从下到上执行) ================
        //5. 协议编码器 (JT808Message -> ByteBuf)
        pipeline.addLast("encoder", new JT808Encoder());
        // 6. 异常处理器
        pipeline.addLast("exceptionHandler", new JT808ExceptionHandler());
    }

    /**
     * 初始化阶段的异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("通道初始化失败: {}", ctx.channel().remoteAddress(), cause);
        ctx.close();
    }

}
